package com.baizhi.user.controller;


import com.baizhi.user.entity.Menu;
import com.baizhi.user.entity.ResultEntity;
import com.baizhi.user.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author zhenggang
 * @since 2022-02-24
 */
@RestController
@RequestMapping("/resource")
public class MenuController {
    @Autowired
    private IMenuService ms;
    @GetMapping("/showUserMenu")
    public ResultEntity<List<Menu>> showUserMenu(){
        // toDo 后期需要动态获取当前登陆人编号
        int adminId=1;
        List<Menu> menus = ms.selectMyMenu(adminId);
        //去查询出adminId为1的用户所有的一级权限和二级权限，整理成一个树状结构
        return ResultEntity.ok(menus);
    }

    @GetMapping("/showAllResourceTree")
    public ResultEntity showAllResourceTree(){
        List<Menu> menuList = ms.list();//所有的菜单数据
        //先过滤出来一级菜单
        List<Menu> menuTree = menuList.stream().filter((m) -> {return m.getType() == 0;})
                .peek((m) -> {
                    m.setChildMenuList(getChildren(m.getMenuId(), menuList));
                }).collect(Collectors.toList());
        return ResultEntity.ok(menuTree);
    }
    //找孩子的，第一个参数是要找孩子的菜单的id,第二个参数是数据源
    private List<Menu> getChildren(Long mid,List<Menu> menuList){
        return menuList.stream().filter((m)->{return m.getParentId().equals(mid);})
                .peek((m)->{m.setChildMenuList(getChildren(m.getMenuId(),menuList));})
                .collect(Collectors.toList());
    }
}

